package com.spring;

import java.io.File;
import java.lang.annotation.Annotation;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class CsyApplicationContext {
    private Class configClass;//spring容器类
    private ConcurrentHashMap<String,Object> singgletonObjects =new ConcurrentHashMap<>();//单例池
    private ConcurrentHashMap<String,BeanDefinnition> beanDefinnitionMap =new ConcurrentHashMap<>();
    private List<BeanPostProcessor> beanPostProcessorsList =new ArrayList<>();

    public CsyApplicationContext(Class configClass) {//传进配置类
        this.configClass = configClass;
        //解析配置类
        //ComponentScan注解--->扫描路径--->扫描--->Beandefinition--->BeanDefinitionMap

        scan(configClass);

        for (Map.Entry<String,BeanDefinnition> entry: beanDefinnitionMap.entrySet()) {
            String beanName=entry.getKey();
            BeanDefinnition beanDefinnition=entry.getValue();


            if(beanDefinnition.getScope().equals("singleton")){
                Object bean = craeteBean(beanName,beanDefinnition);
                singgletonObjects.put(beanName,bean);//把当前的beanName和创建的Bean放进单例池


            }
        }

    }
    public  Object craeteBean(String beanName,BeanDefinnition beanDefinnition){
        //根据bean的定义创建bean的对象
        Class clazz = beanDefinnition.getClazz();
        try {
            Object instance = clazz.getDeclaredConstructor().newInstance();
            //依赖注入
            for (Field declaredField : clazz.getDeclaredFields()) {

                if(declaredField.isAnnotationPresent(Autowired.class)){
                    Object bean = getBean(declaredField.getName());
                    declaredField.setAccessible(true);
                    declaredField.set(instance,bean);
                }
            }
            //Aware回调
            if(instance instanceof BeanNameAware){
                ((BeanNameAware)instance).setBeanName(beanName);
            }
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorsList) {
                instance=beanPostProcessor.postProcessBeforeInitialization(instance,beanName);

            }
            //初始化
            if(instance instanceof InitializingBean){
                try {
                    ((InitializingBean)instance).afterPropertiesSet();
                } catch (Exception e) {
                    throw new RuntimeException(e);
                }

            }
            for (BeanPostProcessor beanPostProcessor : beanPostProcessorsList) {
                instance=beanPostProcessor.postProcessAfterInitialization(instance,beanName);

            }

            //BeanPostProcessor

            return instance;
        } catch (InstantiationException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        } catch (InvocationTargetException e) {
            throw new RuntimeException(e);
        } catch (NoSuchMethodException e) {
            throw new RuntimeException(e);
        }



    }

    private void scan(Class configClass) {
        ComponentScan componentScanAnnotation = (ComponentScan) configClass.getDeclaredAnnotation(ComponentScan.class);
        //拿到ComponenrScan注解
        String path = componentScanAnnotation.value();//扫描路径
        System.out.println(path);

        //扫描
        //类加载器
        //Bootstrap--->jre/lib
        //Ext--->jre/ext/lib
        //App-------->classpath--->
        path=path.replace(".","/");//把路径的.改成/
        ClassLoader classLoader=CsyApplicationContext.class.getClassLoader();//app
        URL resource=classLoader.getResource(path);//拿到资源目录
        File file=new File(resource.getFile());
        if(file.isDirectory()){
          File[] files=file.listFiles();
            for (File file1 : files) {
                String fileName=file1.getAbsolutePath();
                if(fileName.endsWith(".class")){
                String className=fileName.substring(fileName.indexOf("com"),fileName.indexOf(".class"));//截掉多余的路径
                className =className.replace("\\",".");



                    try {
                        Class<?> clazz = classLoader.loadClass((className));
                        if(clazz.isAnnotationPresent(Component.class)){
                            //如果有Component注解表示当前这个类是一个Bean
                            //创建Bean对象
                            //解析类，判断当前bean是单例bean，还有protottype的bean
                            //BeanDefinition
                            if (BeanPostProcessor.class.isAssignableFrom(clazz)) {
                                try {
                                    BeanPostProcessor instance = (BeanPostProcessor) clazz.getDeclaredConstructor().newInstance();
                                    beanPostProcessorsList.add(instance);
                                } catch (InstantiationException e) {
                                    throw new RuntimeException(e);
                                } catch (IllegalAccessException e) {
                                    throw new RuntimeException(e);
                                } catch (InvocationTargetException e) {
                                    throw new RuntimeException(e);
                                } catch (NoSuchMethodException e) {
                                    throw new RuntimeException(e);
                                }
                            }

                            Component componentAnnotstion = clazz.getDeclaredAnnotation(Component.class);
                            String beanName=componentAnnotstion.value();
                            BeanDefinnition beanDefinnition=new BeanDefinnition();
                            beanDefinnition.setClazz(clazz);
                            if(clazz.isAnnotationPresent(Scope.class)){
                                Scope scopeAnnotation =clazz.getDeclaredAnnotation(Scope.class);
                                beanDefinnition.setScope(scopeAnnotation.value());
                            }else {
                                beanDefinnition.setScope("singleton");
                            }
                            beanDefinnitionMap.put(beanName,beanDefinnition);//扫描到所有bean的定义

                        }
                    } catch (ClassNotFoundException e) {
                        throw new RuntimeException(e);
                    }
                 }

            }


        }
    }

    public Object getBean(String beanName){
        if(beanDefinnitionMap.containsKey(beanName)){
            BeanDefinnition beanDefinnition =beanDefinnitionMap.get(beanName);
            if(beanDefinnition.getScope().equals("singleton")){//如果是单例bean
                Object o = singgletonObjects.get(beanName);
                return o;

            }else {//如果不是单例bean是原型bean
                //创建Bean对象
                Object bean=craeteBean(beanName,beanDefinnition);
                return bean;

            }

        }else {
            //不存在对应的bean
            throw new NullPointerException();
        }

    }
}
